<script setup lang="ts" name="Header">
import { ref, computed, watch, onMounted } from 'vue'
import { nevList } from '@/config/header'
import { RouterLink, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import Modal from '@/components/Auth/Modal.vue'
import LoginForm from '@/components/Auth/LoginForm.vue'
import RegisterForm from '@/components/Auth/RegisterForm.vue'
import ColorPicker from '@/components/Theme/ColorPicker.vue'
import SearchBar from '@/components/search/SearchBar.vue'
import { ElMessage } from 'element-plus'

const keyword = ref('')
const router = useRouter()
const modalRef = ref(null)
const showLogin = ref(true)
const userStore = useUserStore()

// 计算属性：判断用户是否已登录
const isLoggedIn = computed(() => userStore.isLoggedIn)

// 计算属性：获取用户名
const username = computed(() => userStore.username)

// 监听登录状态变化
watch(
  () => isLoggedIn.value,
  (newValue) => {
    if (newValue) {
      userStore.checkAndUpdateUserInfo()
    }
  }
)

// 处理搜索
const handleSearch = (keyword: string) => {
  if (keyword.trim()) {
    router.push({
      path: '/search',
      query: { keyword }
    }).then(() => {
      // 获取搜索页面组件实例
      const searchComponent = router.currentRoute.value.matched[0]?.instances?.default
      // 如果存在搜索方法，则执行搜索
      if (searchComponent && 'handleSearch' in searchComponent) {
        searchComponent.handleSearch(keyword)
      }
    })
  }
}

const openModal = () => {
  if (!isLoggedIn.value) {
    modalRef.value?.openModal()
  }
}

const toggleForm = () => {
  showLogin.value = !showLogin.value
}

const resetForms = () => {
  const currentForm = showLogin.value ? loginFormRef.value : registerFormRef.value
  if (currentForm?.resetForm) {
    currentForm.resetForm()
  }
}

const loginFormRef = ref(null)
const registerFormRef = ref(null)

// 添加控制下拉菜单显示的状态
const showDropdown = ref(false)

// 切换下拉菜单显示状态
const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value
}

// 关闭下拉菜单
const closeDropdown = () => {
  showDropdown.value = false
}

// 处理登出并关闭下拉菜单
const handleLogout = () => {
  userStore.logout()
  closeDropdown()
}

// 添加上传背景的处理函数
const handleBackgroundUpload = async (event) => {
  const input = event.target
  const file = input.files?.[0]
  
  if (!file) return
  
  try {
    const result = await userStore.uploadBackground(file)
    if (result.success) {
      ElMessage.success('背景上传成功')
    } else {
      ElMessage.error(result.message || '上传失败')
    }
  } catch (err) {
    console.error('上传背景失败:', err)
    ElMessage.error('上传失败')
  } finally {
    // 清空 input 值，允许重复上传同一文件
    input.value = ''
  }
}

const themeModalRef = ref(null)

// 更新主题色
const updateTheme = async (color: string) => {
  try {
    const result = await userStore.updateBackgroundColor(color)
    if (result.success) {
      themeModalRef.value?.closeModal()
      ElMessage.success('主题更新成功')
    } else {
      ElMessage.error(result.message || '主题更新失败')
    }
  } catch (error) {
    console.error('更新主题色失败:', error)
    ElMessage.error('主题更新失败')
  }
}
</script>

<template>
  <div class="page-header">
    <div class="header-container">
      <!-- 左侧 Logo -->
      <div class="header-logo">
      <img src="/logo.png" alt="logo">
        <span>MusicPlayer</span>
      </div>

      <!-- 中间导航 -->
      <nav class="header-nav">
        <RouterLink 
          v-for="item in nevList" 
          :key="item.title"
          :to="item.path"
          class="nav-item"
        >
          {{ item.title }}
        </RouterLink>
      </nav>

      <!-- 右侧工具栏 -->
      <div class="header-tools">
        <div class="header-search">
          <SearchBar @search="handleSearch" />
        </div>
        
        <!-- 用户区域 -->
        <div class="user-section">
          <template v-if="isLoggedIn">
            <div class="user-menu">
              <div 
                class="username" 
                @click="toggleDropdown"
              >
                {{ username }}
              </div>
              <div 
                class="menu-dropdown" 
                :class="{ 'show': showDropdown }"
                v-show="showDropdown"
                @mouseleave="closeDropdown"
              >
                <div class="menu-item theme-setting" @click="themeModalRef?.openModal()">
                  <span>主题设置</span>
                </div>
                <div class="menu-item upload-bg">
                  <label class="upload-label">
                    上传背景
                    <input
                      type="file"
                      accept="image/jpeg,image/png,image/gif"
                      class="upload-input"
                      @change="handleBackgroundUpload"
                    >
                  </label>
                </div>
                
                <button class="logout-btn" @click="handleLogout">
                  退出登录
                </button>
              </div>
            </div>
          </template>
          <button v-else class="login-btn" @click="openModal">
            登录
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- 模态框 -->
  <Modal ref="modalRef" @reset-forms="resetForms">
    <LoginForm 
      v-if="showLogin" 
      ref="loginFormRef"
      :modalRef="modalRef"
      @switch-form="toggleForm"
    />
    <RegisterForm 
      v-else 
      ref="registerFormRef"
      :modalRef="modalRef"
      @switch-form="toggleForm"
    />
  </Modal>

  <Modal ref="themeModalRef">
    <ColorPicker 
      :modalRef="themeModalRef"
      @update-theme="updateTheme"
    />
  </Modal>
</template>

<style scoped lang="scss">
.page-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 64px;
  background: color-mix(in srgb, var(--bgc-color-2) 60%, transparent);
  backdrop-filter: blur(20px);
  z-index: 1000;
  border-bottom: 1px solid rgba(255,255,255,0.08);
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);

  .header-container {
    max-width: 1200px;
    height: 100%;
    margin: 0 auto;
    padding: 0 20px;
    display: flex;
    align-items: center;
    gap: 40px;

    // Logo
    .header-logo {
      display: flex;
      align-items: center;
      gap: 12px;
      
      img {
        width: 40px;
        height: 40px;
        transition: all 0.3s ease;
        
        &:hover {
          transform: scale(1.05);
          filter: drop-shadow(0 0 8px color-mix(in srgb, var(--primary-color) 30%, transparent));
        }
      }
      
      span {
        color: var(--primary-color);
        font-size: 24px;
        font-weight: 600;
        letter-spacing: 1px;
        background: linear-gradient(to right, var(--primary-color), color-mix(in srgb, var(--primary-color) 85%, white));
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        text-shadow: 0 2px 4px color-mix(in srgb, var(--primary-color) 10%, transparent);
      }
    }

    // 导航
    .header-nav {
      flex: 1;
      display: flex;
      gap: 30px;

      .nav-item {
        color: var(--secondary-color);
        font-size: 16px;
        transition: all 0.3s ease;
        padding: 6px 12px;
        border-radius: 8px;
        position: relative;

        &:hover {
          color: var(--primary-color);
          background: color-mix(in srgb, var(--primary-color) 10%, transparent);
        }

        &.router-link-active {
          color: var(--primary-color);
          background: color-mix(in srgb, var(--primary-color) 15%, transparent);
          font-weight: 500;
          
          &::after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 50%;
            transform: translateX(-50%);
            width: 20px;
            height: 3px;
            background: linear-gradient(to right, var(--primary-color), transparent);
            border-radius: 2px;
          }
        }
      }
    }

    // 工具栏
    .header-tools {
      display: flex;
      align-items: center;
      gap: 20px;

      .header-search {
        :deep(.search-bar) {
          margin: 0;
          max-width: none;
          width: 200px;

          .search-input-wrapper {
            height: 32px;
            position: relative;
          }

          .search-input {
            height: 32px;
            padding: 0 16px;
            font-size: 14px;
            background: color-mix(in srgb, var(--bgc-color-2) 40%, transparent);
            border-color: color-mix(in srgb, var(--primary-color) 10%, transparent);
            border-radius: 16px;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);

            &:focus {
              background: color-mix(in srgb, var(--bgc-color-2) 60%, transparent);
              border-color: color-mix(in srgb, var(--primary-color) 30%, transparent);
              box-shadow: 0 2px 12px color-mix(in srgb, var(--theme-color) 15%, transparent);
            }

            &::placeholder {
              color: color-mix(in srgb, var(--primary-color) 50%, transparent);
            }
          }

          .search-button {
            display: none; // 隐藏搜索按钮，使用回车搜索
          }

          .suggestions-list {
            margin-top: 8px;
            border-color: color-mix(in srgb, var(--primary-color) 10%, transparent);
            background: color-mix(in srgb, var(--bgc-color-2) 95%, transparent);
            border-radius: 12px;
            backdrop-filter: blur(20px);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            
            .suggestion-item {
              padding: 10px 16px;
              border-bottom: 1px solid color-mix(in srgb, var(--primary-color) 5%, transparent);
              
              &:last-child {
                border-bottom: none;
              }
              
              &:hover {
                background: color-mix(in srgb, var(--theme-color) 8%, transparent);
              }
              
              .title {
                color: var(--primary-color);
                font-weight: 500;
              }
              
              .artist {
                color: color-mix(in srgb, var(--primary-color) 60%, transparent);
                font-size: 0.9em;
              }
            }
          }
        }
      }

      .user-section {
        display: flex;
        align-items: center;

        .user-menu {
          position: relative;
          
          .username {
            color: var(--primary-color);
            font-size: 14px;
            padding: 6px 12px;
            background: color-mix(in srgb, var(--hover-color) 10%, transparent);
            border-radius: 16px;
            transition: all 0.3s ease;
            cursor: pointer;
            
            &:hover {
              background: color-mix(in srgb, var(--hover-color) 20%, transparent);
            }
          }

          .menu-dropdown {
            position: absolute;
            top: 100%;
            right: 0;
            margin-top: 8px;
            min-width: 140px;
            background: var(--bgc-color-1);
            border: 1px solid color-mix(in srgb, var(--primary-color) 8%, transparent);
            border-radius: 12px;
            padding: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            opacity: 0;
            transform: translateY(-10px);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            pointer-events: none;

            &.show {
              opacity: 1;
              transform: translateY(0);
              pointer-events: auto;
            }

            &::before {
              content: '';
              position: absolute;
              top: -5px;
              right: 20px;
              width: 10px;
              height: 10px;
              background: var(--bgc-color-1);
              border-left: 1px solid color-mix(in srgb, var(--primary-color) 8%, transparent);
              border-top: 1px solid color-mix(in srgb, var(--primary-color) 8%, transparent);
              transform: rotate(45deg);
            }

            .menu-item {
              width: 100%;
              padding: 10px 16px;
              border-radius: 8px;
              transition: all 0.3s ease;
              
              &:not(:last-child) {
                margin-bottom: 4px;
              }
            }
            
            .upload-bg {
              .upload-label {
                display: block;
                width: 100%;
                color: var(--primary-color);
                font-size: 14px;
                cursor: pointer;
                white-space: nowrap;
                transition: all 0.3s ease;
                
                &:hover {
                  color: var(--theme-color);
                }
              }
              
              .upload-input {
                display: none;
              }
              
              &:hover {
                background: color-mix(in srgb, var(--theme-color) 8%, transparent);
              }
            }
            
            .logout-btn {
              width: 100%;
              padding: 10px 16px;
              color: #ff4444;
              background: none;
              border: none;
              border-radius: 8px;
              font-size: 14px;
              text-align: left;
              cursor: pointer;
              white-space: nowrap;
              transition: all 0.3s ease;

              &:hover {
                background: color-mix(in srgb, #ff4444 8%, transparent);
                color: #ff6666;
              }
            }

            .theme-setting {
              color: var(--primary-color);
              font-size: 14px;
              cursor: pointer;
              
              &:hover {
                background: color-mix(in srgb, var(--theme-color) 8%, transparent);
                color: var(--theme-color);
              }
            }
          }
        }

        .login-btn {
          padding: 6px 16px;
          background: linear-gradient(
            145deg,
            var(--hover-color),
            color-mix(in srgb, var(--hover-color) 90%, black)
          );
          color: var(--primary-color);
          border: none;
          border-radius: 20px;
          font-size: 14px;
          cursor: pointer;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px color-mix(in srgb, var(--hover-color) 30%, transparent);
          }
          
          &:active {
            transform: translateY(0);
          }
        }
      }
    }
  }
}
</style>
